package com.hy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.handler.BusinessException;
import com.hy.response.ResultCode;
import com.hy.system.entity.Department;
import com.hy.system.entity.User;
import com.hy.system.mapper.DepartmentMapper;
import com.hy.system.mapper.UserMapper;
import com.hy.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.hy.system.enums.UserStatusEnum;
import com.hy.system.enums.UserTypeEnum;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author hy
 * @since 2021-04-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public IPage<User> findUserPage(Page<User> page, Wrapper<User> queryWrapper) {
        return this.baseMapper.findUserPage(page,queryWrapper);
    }

    @Override
    public void addUser(User user) {
        //判断是否增加了同一个用户
        String username = user.getUsername();
        //获取部门
        Long departmentId = user.getDepartmentId();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Integer count = this.baseMapper.selectCount(wrapper);
        if(count!=0){
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        Department department = departmentMapper.selectById(departmentId);
        if(department==null){
            throw new BusinessException(ResultCode.DEPARTMENT_NOT_EXIST.getCode(),
                    ResultCode.DEPARTMENT_NOT_EXIST.getMessage());
        }
        String salt = UUID.randomUUID().toString().substring(0,32);
        //user.setSalt(salt); //security自动加盐，所以不用这个字段了
        //没有设置创建时间和更新时间  使用mybatis-plus的自动填充功能实现
        //user.setCreateTime(new Date());
        //user.setModifiedTime(new Date());
        //使用spring security自带的密码加密策略
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //用户类型
        user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());
        //设置状态
        user.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());
        //设置是否删除
        user.setDeleted(false);
        this.baseMapper.insert(user);
    }

    @Override
    public void downLoadXlsxByPoi(HttpServletResponse response) throws Exception {
        //        1.创建一个空的工作薄
        //XSSFWorkbook workbook = new XSSFWorkbook();
        //直接用Workbook类型来接收，不带XSSF，这样改新老版本只要改后面的XSSF就行了，XSSFSheet类似
        Workbook workbook = new XSSFWorkbook();
        //        2.在工作薄中创建一个工作表
        Sheet sheet = workbook.createSheet("用户数据");
        //        3.处理标题
        String[] titles = new String[]{"编号","用户名","昵称","性别","电话","状态","创建时间","修改时间","类型","所属部门"};
        //        4.创建标题行
        Row titleRow = sheet.createRow(0);
        Cell cell = null;
        for (int i = 0; i < titles.length; i++) {
            cell = titleRow.createCell(i);
            cell.setCellValue(titles[i]);
        }
        //        5.处理内容
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.eq("deleted",0);
        List<User> userList = userMapper.selectList(null);
        int rowIndex = 1;
        Row row = null;
        for (User user : userList) {
//      for(int i=0;i<userList.size();i++){
//          User user = userList.get(i);
            row = sheet.createRow(rowIndex);

            cell = row.createCell(0);
            cell.setCellValue(user.getId());

            cell = row.createCell(1);
            cell.setCellValue(user.getUsername());

            cell = row.createCell(2);
            cell.setCellValue(user.getNickname());

            //在这里遇到了印象深刻的问题，很久解决：无论是判断还是toString（），只要为空。就会报空指针。。所以最先要做的就是判断是否为空！！！！！！！！！
            //System.out.println(user.getSex().equals(1));   //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            cell = row.createCell(3);
            //System.out.println("user=>"+user);
            //System.out.println("user.getSex()=>"+user.getSex().toString());
            if(user.getSex()==null){
                cell.setCellValue("保密");
            }else if(user.getSex() == 0){
                cell.setCellValue("女");
            }else if(user.getSex() == 1){
                cell.setCellValue("男");
            }else {
                cell.setCellValue("保密");
            }

            cell = row.createCell(4);
            cell.setCellValue(user.getTel());

            cell = row.createCell(5);
            if(user.getStatus() == 0){
                cell.setCellValue("未禁用");
            }else{
                cell.setCellValue("已禁用");
            }

            cell = row.createCell(6);
            cell.setCellValue(simpleDateFormat.format(user.getCreateTime()));

            cell = row.createCell(7);
            cell.setCellValue(simpleDateFormat.format(user.getModifiedTime()));

            cell = row.createCell(8);
            if(user.getType() == 0){
                cell.setCellValue("超级管理员");
            }else{
                cell.setCellValue("系统用户");
            }

            cell = row.createCell(9);
            //cell.setCellValue(user.getDepartmentId());
            Department department = departmentMapper.selectById(user.getDepartmentId());
            if(department!=null) {
            cell.setCellValue(department.getName());
            }else {
                cell.setCellValue("错误！部门不存在");
            }

            rowIndex++;
        }
        //            6.导出的文件名称
        String filename="用户数据.xlsx";
        //            7.设置文件的打开方式和mime类型
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String(filename.getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        workbook.write(outputStream);

    }
}
